package com.dapeis.api.controller.collocation.impl;

import java.security.InvalidParameterException;
import java.util.Date;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
import com.ag.core.base.Pager;
import com.ag.core.exception.InvalidParamException;
import com.ag.utils.NumberUtils;
import com.ag.utils.json.AGsonBuilder;
import com.dapeis.api.controller.RestController;
import com.dapeis.api.controller.collocation.IPlanController;
import com.dapeis.core.utils.RequirementConfig;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.domain.Plan;
import com.dapeis.exception.StateDisableException;
import com.dapeis.service.COSFileService;
import com.dapeis.service.CollocationPlanService;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

@Controller
@RequestMapping("/dps/plan")
public class PlanControllerImpl extends RestController implements
	IPlanController {
    @Resource
    CollocationPlanService collocationPlanService;
    @Resource
    COSFileService cosFileService;

    /**
     * 查看方案
     */
    @Override
    public JsonElement selectPlan(Integer planId, HttpServletRequest request) {
	Plan collocationPlan = collocationPlanService.selectByPrimaryKey(planId);
	Integer collocationId = getThreadLocalCollocationId();
	if (null	!= collocationPlan) {
	    if (collocationId == collocationPlan.getCollocationId()) {
		    if (collocationPlan.getState().equals(StylistConstants.State.DISABLE)) {
			throw new StateDisableException();
		    }
		JsonObject json = buildSuccess();
		json.add("plan",
			AGsonBuilder.create().toJsonTree(collocationPlan));
		return json;
	    }
	}
	 throw new InvalidParameterException("该用户查询不到此订单");
    }

    /**
     * 保存方案
     * 
     * @throws Exception
     */
    @Override
    public JsonElement savePlan(String planName, String remark,
	    MultipartFile masterImage, String[] imgIds, Integer publish,
	    HttpServletRequest request) throws Exception {
	Plan collocationPlan = new Plan();
	collocationPlan.setCollocationId(getThreadLocalCollocationId());
	// 主图URL
	String filePath = cosFileService.saveFile(masterImage,
		StylistConstants.UploadType.PLAN, request);
	if (null != filePath) {
	    collocationPlan.setMasterImage(filePath);
	} else {
	    throw new InvalidParamException("图片上传失败");
	}
	// 小图id
	String imageIds = null;
	if (null != imgIds && imgIds.length >= 1) {
	    for (String elemt : imgIds) {
		imageIds += elemt + RequirementConfig.SPE_SUX;
	    }
	}
	String ids = parser(imgIds);
	collocationPlan.setImageIds(ids);
	collocationPlan.setCreateTime(new Date().getTime() / 1000);
	collocationPlan.setContent(remark);
	collocationPlan.setPlanName(planName);
	if(publish == StylistConstants.PlanState.SAVE || publish == StylistConstants.PlanState.ISSUE){
		collocationPlan.setPublish(publish);
	}else{
		throw new InvalidParameterException("此状态不存在");
	}
	// Integer id= collocationPlanService.insert(collocationPlan);
	Integer id = collocationPlanService.insert(collocationPlan);
	Plan plan = collocationPlanService.selectByPrimaryKey(id);
	JsonObject json = buildSuccess();
	// json.add("plan", AGsonBuilder.create().toJsonTree(plan));
	return json;
    }

    @Override
    public JsonElement deletePlan(Integer planId, HttpServletRequest request) {
	Plan collocationPlan = collocationPlanService
		.selectByPrimaryKey(planId);
	if (null != collocationPlan) {
	    if (collocationPlan.getState().equals(
		    StylistConstants.State.DISABLE)) {
		throw new StateDisableException();
	    }
	    collocationPlan.setState(StylistConstants.State.DISABLE);
	    collocationPlanService.updateByPrimaryKeySelective(collocationPlan);
	    JsonObject json = buildSuccess();
	    return json;
	}
	throw new InvalidParameterException("查询不到方案信息ID:" + planId);
    }

    @Override
    public JsonElement list(Integer p, HttpServletRequest request) {
	Pager pager = new Pager();
	Integer userId = getThreadLocalCollocationId();
	Example example = new Example(Plan.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(Plan.PROPERTY_STATE, StylistConstants.State.NORMAL);
	criteria.andEqualTo(Plan.PROPERTY_ISSUE,
		StylistConstants.PlanState.ISSUE);
	criteria.andEqualTo(Plan.PROPERTY_COLLOCATIONID, userId);
	
	pager.setExample(example);
	if (NumberUtils.isValid(p)) {
	    pager.setCurrentPage(p);
	}
	collocationPlanService.pager(pager);
	JsonObject result = buildSuccess();
	result.add("pager", AGsonBuilder.create().toJsonTree(pager));
	return result;
    }

    @Override
	public JsonElement darftList(Integer p, HttpServletRequest request) {
    	Pager pager = new Pager();
    	Integer userId = getThreadLocalCollocationId();
    	Example example = new Example(Plan.class);
    	Criteria criteria = example.createCriteria();
    	criteria.andEqualTo(Plan.PROPERTY_STATE, StylistConstants.State.NORMAL);
    	criteria.andEqualTo(Plan.PROPERTY_ISSUE,StylistConstants.PlanState.SAVE);
    	criteria.andEqualTo(Plan.PROPERTY_COLLOCATIONID, userId);
    	pager.setExample(example);
    	if (NumberUtils.isValid(p)) {
    	    pager.setCurrentPage(p);
    	}
    	collocationPlanService.pager(pager);
    	JsonObject result = buildSuccess();
    	result.add("pager", AGsonBuilder.create().toJsonTree(pager));
    	return result;
	}
    
    /**
     * 解析数组，拼装
     * 
     * @param arr
     * @return
     */
    public String parser(String[] arr) {
	String str = "";
	if (null != arr && arr.length >= 1) {
	    for (String elemt : arr) {
		str += elemt + RequirementConfig.SPE_SUX;
	    }
	}
	return str;
    }
}
